package com.moli.lumpSugar.user.event.listener;


import com.moli.lumpSugar.common.cache.user.UserCache;
import com.moli.lumpSugar.user.dao.UserDao;
import com.moli.lumpSugar.user.domain.entity.User;
import com.moli.lumpSugar.user.domain.enums.ActiveStatusEnum;
import com.moli.lumpSugar.user.event.LoginSuccessEvent;
import com.moli.lumpSugar.user.service.IpService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * @program: LumpSugarChat
 * @description: 用户注册事件监听者
 * @author: zhangjt
 * @create: 2024-10-25 17:21
 **/
@Component
public class LoginSuccessEventListener {
    @Autowired
    private IpService ipService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserCache userCache;
//    @Autowired
//    private PushService pushService;
//    @Autowired
//    private WSAdapter wsAdapter;

    @TransactionalEventListener(value = LoginSuccessEvent.class, phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
    public void refreshIpInfo(LoginSuccessEvent loginSuccessEvent) {
        User user = loginSuccessEvent.getUser();
        User updateInfoUser = new User();
        updateInfoUser = updateInfoUser.builder()
                .id(user.getId())
                .lastOptTime(user.getLastOptTime())
                .ipInfo(user.getIpInfo())
                .activeStatus(ActiveStatusEnum.ONLINE.getType())
                .build();
        userDao.updateById(updateInfoUser);
        ipService.refreshIpDetailAsync(user.getId());
    }

    @Async
    @EventListener(classes = LoginSuccessEvent.class)
    public void saveRedisAndPush(LoginSuccessEvent event) {
        User user = event.getUser();
        userCache.online(user.getId(), user.getLastOptTime());
//        pushService.sendPushMsg(wsAdapter.buildOnlineNotifyResp(event.getUser()));
    }

}
